const mysql = require('mysql')
const config = require('../app/config')
const dbConfig = {
  host: config.MYSQL_HOST,
  user: config.MYSQL_USER,
  password: config.MYSQL_PASSWORD,
  database: config.MYSQL_DATABASE,
  multipleStatements: true,//可执行多条sql语句
}
const query = function (sql, loc) {
  const connection = mysql.createConnection(dbConfig)
  return new Promise((resolve, reject) => {
    connection.connect(err => {
      if (err) reject('DATABASE ERROR:connection failed!')
    })
    connection.query(sql, loc, (err, res) => {
      if (err) {
        reject(`DATABASE ERROR:${err.message}`)
      }
      resolve(res)
    })
    connection.end(err => {
      reject('DATABASE ERROR:close connection failed!')
    })
  })
}

module.exports = query
